package org.jet.emall.security.vote;

import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;

import org.springframework.security.web.FilterInvocation;

import java.util.Collection;



/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-09 11:40
 */
public class RestfulUrlVote implements AccessDecisionVoter<FilterInvocation> {


    private final String ROLE_ANONYMOUS = "ROLE_ANONYMOUS";


    @Override
    public boolean supports(ConfigAttribute attribute) {

        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    /**
     *
     * @param authentication
     * @param object
     * @param attributes 原来的权限相关的属性，因为我们要做动态权限，对字符串形式的属性不适我们，所以这个参数没用上
     * @return
     */
    @Override
    public int vote(Authentication authentication, FilterInvocation object, Collection<ConfigAttribute> attributes) {
        //放行permitAll配置
        if( attributes!=null && !attributes.isEmpty()){
            for(ConfigAttribute attribute : attributes){
                if("permitAll".equals(attribute.toString())){
                    System.out.println("通过PermitAll授权通过");
                    return ACCESS_GRANTED;
                }
            }
        }
        if(authentication==null || authentication instanceof AnonymousAuthenticationToken){
            System.out.println("授权失败");
            return ACCESS_DENIED;
        }
        System.out.println("授权通过,url="+object.getRequestUrl());
        return ACCESS_GRANTED;
    }
}
